package com.codedancer.campus.common.utils;

import com.codedancer.campus.common.exception.BusinessException;
import com.codedancer.campus.common.model.mail.EmailSendModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class EmailUtil {

    @Autowired
    private JavaMailSender mailSender;

    // 发送人
    @Value("${spring.mail.username}")
    private String sendEmail;

    /**
     * 发送验证码
     *
     * @param sendModel
     */
    public void sendEmailCode(EmailSendModel sendModel) {
        try {
            log.info("开始发送用户注册邮件验证码");
            // 创建邮件消息
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(sendEmail);
            message.setTo(
                sendModel.getReceiverEmails()
                    .toArray(new String[sendModel.getReceiverEmails().size()]));
            message.setSubject(sendModel.getSubject());
            message.setText(sendModel.getContent());
            mailSender.send(message);
            log.info("用户注册邮件验证码发送成功");
        } catch (Exception e) {
            log.info("用户注册邮件验证码发送失败，失败原因：{}", e.getMessage());
            throw new BusinessException("用户注册邮件验证码发送失败");
        }
    }
}
